package com.zlp.config;

import com.zlp.entity.SysResource;
import com.zlp.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * SpringSecurity需要的用户详情
 * Created by macro on 2018/4/26.
 */
@Service("myUserDetails")
@Slf4j
public class MyUserDetails implements UserDetails {

    private SysUser sysUser;
    private List<SysResource> sysResourceList;


    public MyUserDetails(SysUser sysUser, List<SysResource> sysResourceList) {
        this.sysUser = sysUser;
        this.sysResourceList = sysResourceList;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        log.info("获取用户权限===========>");
        //返回当前用户的权限
        return sysResourceList.stream()
                .filter(permission -> StringUtils.isNotEmpty(permission.getButtonPermission()))
                .map(permission -> new SimpleGrantedAuthority(permission.getButtonPermission()))
                .collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return sysUser.getPassword();
    }

    @Override
    public String getUsername() {
        log.info("userCode:{}",sysUser.getUserCode());
        return sysUser.getUserCode();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return sysUser.getStatus().equals(1);
    }
}
